package org.yiming.tools.mqtt.client.client.command;

import lombok.extern.slf4j.Slf4j;
import org.yiming.tools.mqtt.client.ApplicationContext;
import org.yiming.tools.mqtt.client.client.MqttClient;

import java.util.concurrent.Future;
import java.util.regex.Pattern;

/**
 * @author renwenpeng
 * date  2022/3/25 4:50 下午
 */
@Slf4j
public class PublishCommand extends AbstractMqttCommand {

    private final String[] names = new String[]{"pub", "publish"};

    public PublishCommand(ApplicationContext applicationContext) {
        super(applicationContext);
    }

    @Override
    public String[] name() {
        return names;
    }

    @Override
    int argsMinLength() {
        return 2;
    }

    @Override
    String apply(MqttClient mqttClient, String[] args) {
        boolean isSuccess;
        Future<Boolean> publish = null;
        try {
            publish = mqttClient.publish(args[0], args[1]
                    // 消息质量
                    , args.length > 2 && Pattern.matches("[0-2]", args[2])
                            ? Integer.parseInt(args[2])
                            : 1);
            if (publish != null) {
                isSuccess = publish.get();
                return String.format("[%s] %s", mqttClient.getName(), isSuccess ? "success" : "fail");
            } else {
                return String.format("[%s] this client is error", mqttClient.getName());
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (publish != null && !publish.isCancelled() && !publish.isDone()) {
                publish.cancel(true);
            }
        }
        return null;
    }

    @Override
    public String[] helpContent() {
        return new String[]{"pub/publish", "{topic} {content} ?{qos:1}"};
    }
}
